import { login, getUserInfo} from '@/api/login';
const user = {
    state: {//定义全局变量
        token: '',
        roles: '',
        name: '',
        userId: '',
        avatar: '',
        uuid: '',
        userInfo: {},
    },
    mutations: {//使用提交commit可以修改全局变量（同步）
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_USERID: (state, id) => {
            state.userId = id
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_UUID: (state, uuid) => {
            state.uuid = uuid
        },
        SET_USERINFO: (state, data) => {
            state.userInfo = data
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        }
    },
    actions: { //全局方法（修改全局变量的方法，可以异步）
        Login ({ commit }, userInfo) {
            const UName = userInfo.UName.trim()
            const UPass = userInfo.UPass
            return new Promise((resolve, reject) => {
                let data = {
                    UName,
                    UPass
                }
                login(data).then(res => {
                    if (res.success) {
                        sessionStorage.setItem('Token', res.data.token)
                        commit('SET_TOKEN', res.data.token)
                        resolve(res)
                    } else {
                        reject(res)
                    }
                }).catch(err => console.log( reject(err)))
            })
        },
        getUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo(state.token).then(res => {
                    if (res) {
                        if (res.success) {
                            const avatar = res.data.avatar == '' ? require("@/assets/profile.png") : res.data.avatar
                            commit('SET_AVATAR', avatar)
                            commit('SET_UUID', res.data.uuid)
                            commit('SET_USERID', res.data.UID)
                            commit('SET_NAME', res.data.UName)
                            commit('SET_USERINFO', res.data)
                            commit('SET_ROLE', res.data.user_role)
                            resolve(res)
                        } else {
                            reject(res)
                        }
                    }


                }).catch(err => {
                    reject(err)
                })
            })
        },
        setRole({ commit }) {
            return new Promise((resolve, reject) => {
                console.log(reject)
                commit('SET_ROLES', 1)
                resolve(1)
            })
        }
    }
}

export default user